from datetime import datetime

import requests
from flask import request, jsonify
import os


def register_file_routes(app):
    @app.route('/plantACR/uploadFiles', methods=['POST'])
    def upload_files():
        resultVO = {
            "code": 200,
            "data": {
                "uploadResult": {
                    "success_count": 0,
                    "fail_count": 0,
                    "success_files": [],
                    "fail_files": [],
                    "message": ""
                }
            },
            "message": ""
        }
        # 生成不重复的保存数据集文件(名字)
        current_time = datetime.now().strftime("%Y_%m%d_%H%M%S")  # 2025_0412_163021
        try:
            # 获取用户名称（测试传文件顺带传参数，后期没用到）
            user_name = request.form.get('user_name')
            print('user_name:', user_name)

            # 获取上传的文件列表
            files = request.files.getlist('files')
            print('files:', files)

            # 检查文件是否存在
            if not files:
                resultVO["code"] = 400
                resultVO["data"]["uploadResult"]["message"] = "未接收到文件"
                resultVO["message"] = "未接收到文件"
                return jsonify(resultVO)

            for file in files:
                if file:
                    try:
                        # 原文件名
                        original_filename = os.path.splitext(file.filename)[0]  # 不带后缀
                        # 获取文件后缀
                        file_ext = os.path.splitext(file.filename)[1]  # 如".bed"
                        # 生成带序号、时间戳和原后缀的文件名
                        filename = f"{original_filename}_{current_time}{file_ext}"
                        # 保存文件到指定缓存目录
                        upload_dir = 'ACRmodel/static/temp'
                        if not os.path.exists(upload_dir):
                            os.makedirs(upload_dir)  # 自动创建目录
                        file_path = os.path.join(upload_dir, filename)
                        file.save(file_path)

                        # 正常处理
                        resultVO["data"]["uploadResult"]["success_count"] += 1
                        resultVO["data"]["uploadResult"]["success_files"].append(filename)

                        # 特殊处理：假设test3.bed文件上传失败，测试错误提示
                        # if filename.lower() != 'test3.bed':
                        #     resultVO["data"]["uploadResult"]["success_count"] += 1
                        #     resultVO["data"]["uploadResult"]["success_files"].append(filename)
                        # else:
                        #     resultVO["data"]["uploadResult"]["fail_count"] += 1
                        #     resultVO["data"]["uploadResult"]["fail_files"].append(file.filename)
                        #     print(f"测试文件 {filename} 已加入失败列表")
                    except Exception as e:
                        print("保存文件异常:", e)
                        resultVO["data"]["uploadResult"]["fail_count"] += 1
                        resultVO["data"]["uploadResult"]["fail_files"].append(file.filename)

            if resultVO["data"]["uploadResult"]["fail_count"] == 0:
                resultVO["data"]["uploadResult"]["message"] = "所有文件上传成功!"
                resultVO["message"] = "所有文件上传成功!"
            elif resultVO["data"]["uploadResult"]["success_count"] == 0:
                resultVO["code"] = 500
                resultVO["data"]["uploadResult"]["message"] = "所有文件上传失败!"
                resultVO["message"] = "所有文件上传失败!"
            else:
                resultVO["code"] = 200
                resultVO["data"]["uploadResult"]["message"] = "部分文件上传成功，部分失败"
                resultVO["message"] = "部分文件上传成功，部分失败"
            return jsonify(resultVO)
        except Exception as e:
            resultVO["code"] = 500
            resultVO["data"]["uploadResult"]["message"] = f"服务器错误，文件上传失败！{str(e)}"
            resultVO["message"] = f"服务器错误，文件上传失败！{str(e)}"
            return jsonify(resultVO)

    @app.route('/plantACR/uploadImage', methods=['POST'])
    def upload_image():
        resultVO = {
            "code": 200,
            "data": {
                "uploadResult": {
                    "success_count": 0,
                    "fail_count": 0,
                    "success_files": [],
                    "fail_files": [],
                    "message": "",
                    "url": ""
                }
            },
            "message": ""
        }
        image_url = ""
        # 生成不重复的保存数据集文件(名字)
        current_time = datetime.now().strftime("%Y_%m%d_%H%M%S")  # 2025_0412_163021
        try:
            # 获取上传的文件列表
            files = request.files.getlist('files')
            print('files:', files)

            # 检查文件是否存在
            if not files:
                resultVO["code"] = 400
                resultVO["data"]["uploadResult"]["message"] = "未接收到文件"
                resultVO["message"] = "未接收到文件"
                return jsonify(resultVO)

            for file in files:
                if file:
                    try:
                        # 原文件名
                        original_filename = os.path.splitext(file.filename)[0]  # 不带后缀
                        # 获取文件后缀
                        file_ext = os.path.splitext(file.filename)[1]  # 如".bed"
                        # 生成带序号、时间戳和原后缀的文件名
                        filename = f"{original_filename}_{current_time}{file_ext}"
                        # 保存文件到指定缓存目录
                        upload_dir = 'ACRmodel/static/picture'
                        if not os.path.exists(upload_dir):
                            os.makedirs(upload_dir)  # 自动创建目录
                        file_path = os.path.join(upload_dir, filename)
                        file.save(file_path)
                        image_url = upload_image_to_imgbed(file_path)

                        # 正常处理
                        resultVO["data"]["uploadResult"]["success_count"] += 1
                        resultVO["data"]["uploadResult"]["success_files"].append(filename)
                        resultVO["data"]["uploadResult"]["url"] = image_url

                    except Exception as e:
                        print("保存文件异常:", e)
                        resultVO["data"]["uploadResult"]["fail_count"] += 1
                        resultVO["data"]["uploadResult"]["fail_files"].append(file.filename)

            if resultVO["data"]["uploadResult"]["fail_count"] == 0:
                resultVO["data"]["uploadResult"]["message"] = "所有文件上传成功!"
                resultVO["data"]["uploadResult"]["url"] = image_url
                resultVO["message"] = "所有文件上传成功!"
            elif resultVO["data"]["uploadResult"]["success_count"] == 0:
                resultVO["code"] = 500
                resultVO["data"]["uploadResult"]["message"] = "所有文件上传失败!"
                resultVO["message"] = "所有文件上传失败!"
            else:
                resultVO["code"] = 200
                resultVO["data"]["uploadResult"]["message"] = "部分文件上传成功，部分失败"
                resultVO["data"]["uploadResult"]["url"] = image_url
                resultVO["message"] = "部分文件上传成功，部分失败"
            return jsonify(resultVO)
        except Exception as e:
            resultVO["code"] = 500
            resultVO["data"]["uploadResult"]["message"] = f"服务器错误，文件上传失败！{str(e)}"
            resultVO["message"] = f"服务器错误，文件上传失败！{str(e)}"
            return jsonify(resultVO)

    def upload_image_to_imgbed(image_path):
        api_url = "https://picui.cn/api/v1/upload"
        headers = {
            "Authorization": "Bearer 970|rZ062rRWL5mQFAKmRejKiito0Acv24iDp3kGWMEv",  # token
            # "Content-Type": "multipart/form-data"
        }
        files = {
            'file': open(image_path, 'rb'),
        }
        data = {
            'token': '970|rZ062rRWL5mQFAKmRejKiito0Acv24iDp3kGWMEv',  # token
            'permission': 1,  # 公开权限，根据需要修改
            # 'strategy_id': YOUR_STRATEGY_ID,  # 储存策略ID
            # 'album_id': YOUR_ALBUM_ID,  # 相册ID
            'expired_at': "2025-09-01 00:00:00"  # 设置过期时间，不能超过一年
        }
        response = requests.post(api_url, headers=headers, files=files, data=data)
        if response.status_code == 200:
            image_result = response.json()
            if image_result["status"]:
                return image_result["data"]["links"]["url"]
            else:
                print(f"图片上传成功但获取URL失败，描述信息: {image_result['message']}")
                return ""
        else:
            print(f"上传图片失败，状态码: {response.status_code}")
            return ""

    return app
